package com.qf.blog.job;

import com.qf.blog.commons.constant.SysConsts;
import com.qf.blog.commons.pool.BlogExecutors;
import com.qf.blog.service.DiscussPostService;
import com.qf.blog.service.IPostScoreService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * User: key
 * ClassName:PostScoreUpdateJob
 * Date: 2023/6/24
 * Time: 23:22
 * description:
 */
@Component
@Slf4j
public class PostScoreUpdateJob {
    @Autowired
    private IPostScoreService postScoreService;
    @Autowired
    private DiscussPostService postService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Scheduled(cron = "0/20 * * * * *")
    public void computeScore() throws InterruptedException {
        BlogExecutors.getPoll().submit(() -> {

            // 1.查询需要计算分数的帖子数量
            Long size = stringRedisTemplate.opsForSet().size(SysConsts.RedisKeys.POST_SCORE_KEY);

            // 2.判断是否为空
            if (size == 0) {
                log.info("本次任务没有要更新的帖子，任务结束");
                return;
            }

            // 3.弹出来(redis中没有了，后期就不用删除了)
            for (int i = 0; i < size; i++) {

                String _postId = stringRedisTemplate.opsForSet().pop(SysConsts.RedisKeys.POST_SCORE_KEY);
                Integer postId = Integer.valueOf(_postId);
                // 4.计算分数
                Double score = postScoreService.computeScore(postId);
                log.info("本次更新帖子id" + postId + "帖子分数" + score);
                // 5.更新帖子的分数
                postService.updateScore(postId, score);
            }
        });
    }
}
